package com.xqq.lottery.util;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import android.os.SystemClock;

import com.xqq.lottery.bean.MessageItem;
import com.xqq.lottery.net.MessageHandle;
import com.xqq.lottery.protocal.MessageType;



public class MessageUtil {
	
	
	public static  ExecutorService receivePoolExecutorService =Executors.newFixedThreadPool(5); //接收线程
	
	public static  ExecutorService activeSingleThreadPool = Executors.newSingleThreadExecutor();
	
	private static Queue<MessageItem> msgQueue =new LinkedList<MessageItem>();
	
	private static long lastHeartTime = 0;  //最后一次收到服务器发回的心跳响应时间
	
    public static void insertSendQueue(MessageItem msgItem){
    	synchronized (msgQueue) {
        	msgQueue.add(msgItem);
        	msgQueue.notify();
		}
    }
    
    public static MessageItem getMsgItem(){
    	synchronized (msgQueue) {
        	while(msgQueue.isEmpty()){
        		try {
    				msgQueue.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
        	}
        	return msgQueue.poll();
		}
    }
    
    /**
     * 根据最后一次收到心跳包的时间
     * @return
     */
    public static boolean isOutTimed(){
    	long elapsedTime = SystemClock.elapsedRealtime()/1000;
    	if(elapsedTime - lastHeartTime > 20){  //20s没收到心跳数据就认为断开链接
    		return false;
    	}
    	return true;
    }
    
    public static void updateHearTime(){
    	lastHeartTime = SystemClock.elapsedRealtime()/1000;
    }
    
    public static void handlMessage(MessageItem msgItem){
    	int msgType = msgItem.getMsgType();
    	switch(msgType){
    	case MessageType.MSG_HEART:  //心跳包数据
    		MessageHandle.handleMessageHeart(msgItem);
    		break;
    	default:
    		break;
    	}
    }
	
}
